<template>
  <view
    v-if="cancelFlag || againBuyFlag || LogisticsFlag || selfFlag || receiveFlag || goPayFlag || deleteShowFlag || showStoreUseBtns"
    class="FooterOrder"
    :style="{ 'marginTop': !!usePlace ? '' : '30rpx' }"
  >
    <view class="footer">
      <view v-if="cancelFlag" class="cancel" @click="showCancel">
        <image src="../../static/image/more.png" />
        <view v-show="newOrderInfo.cancleBtnShow" class="cancelBtn" @click="showPop">取消订单</view>
      </view>
      <view v-else class="cancel" />
      <u-count-down
        v-if="cancelTimeFlag"
        :time="surplusTime"
        format="DD:HH:mm:ss"
        auto-start
        millisecond
        @change="onChange"
      >
        <view class="time">
          剩余时间：
          <text class="time__item">{{ timeData.days }}天</text>
          <text class="time__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours }}时</text>
          <text class="time__item">{{ timeData.minutes }}分</text>
        </view>
      </u-count-down>
      <view class="button">
        <view v-if="againBuyFlag" @click="addShopCar">再次购买</view>
        <view v-if="LogisticsFlag" @click="toLogisticsInfoFn">查看物流</view>
        <view v-if="selfFlag" @click="goDraw">自提信息</view>
        <view v-if="receiveFlag" class="bgbtn" @click="confrimRece">确认收货</view>
        <view v-if="goPayFlag" class="bgbtn" @click="nowPay">立即付款</view>
        <view v-if="deleteShowFlag" @click="deleteOrder">删除订单</view>
        <!-- 线下门店操作按钮 -->
        <template v-if="isStoreOrder">
          <view
            v-if="showConfirmBtn"
            class="btn-order"
            :type="'default'"
            plain="true"
            @click.stop="storeGoPaymentFn(orderInfo.order_id)"
          >去确认</view>
          <view
            v-if="showPayBtn"
            class="btn-order"
            :type="'default'"
            plain="true"
            @click.stop="storeGoPaymentFn(orderInfo.order_id)"
          >去支付</view>
          <view
            v-if="showPackupBtn"
            class="btn-order"
            :type="'default'"
            plain="true"
            @click.stop="storeViewPickingInfoFn(orderInfo.order_id)"
          >提货信息</view>
        </template>
      </view>
    </view>
    <u-modal
      width="540rpx"
      title="订单删除"
      confirm-color="#FF5533"
      :async-close="true"
      :show-cancel-button="true"
      :show="confrimFlag"
      @confirm="confirm"
      @cancel="cancel"
    >
      <view>订单删除后将会进入订单回收箱,可在PC端 - 个人中心 - 回收箱还原！</view>
    </u-modal>
  </view>
</template>

<script>
/*
* sent_type 配送方式;10=快递；20=快运-送货上门；21=快运-站点自提；30=专车包车；40=鑫方盛物流；50=上门自提；52=配送客户自提
* sign_way 签收方式-1电子签收、2纸质签收、3提货码核销，4收银台审核触发已签收、5订单对账、6超时自动确认收货、7正票签收触发已签收、8客户自主确认收货
* */
import { addShopCar, confrimRece, deleteOrder } from '@/api/orderApi';
import { formatDate } from '@/common/common';

export default {
  props: {
    orderInfo: {
      type: Object,
      default: null
    },
    cancleBtnShow: {
      type: Boolean,
      default: false
    },
    platVal: {
      type: Number,
      default: 2
    },
    showTimeFlag: {
      type: Boolean,
      default: true
    },
    date: {
      type: String,
      default: ''
    },
    usePlace: {
      type: String,
      default: ''
    },
    // 当前订单为门店订单，默认为否
    isStoreOrder: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      confrimFlag: false,
      newOrderInfo: this.orderInfo,
      againBuyFlag: false,
      LogisticsFlag: false,
      selfFlag: false,
      receiveFlag: false,
      goPayFlag: false,
      deleteShowFlag: false,
      cancelFlag: false,
      cancelTimeFlag: false,
      code: '',
      timeData: {},
      surplusTime: '', // 计算后的时间戳
    }
  },
  computed: {
    curDate() {
      return this.date
    },
    // 门店订单按钮展示（去确认，去支付，提货信息）
    showStoreUseBtns() {
      return this.showConfirmBtn || this.showPayBtn || this.showPackupBtn
    },
    // 展示门店订单-去确认按钮
    showConfirmBtn() {
      // paid_type == settleType
      const { auditStatus, order_status, xdAccount, billDate, paid_type } = this.orderInfo
      const { loginAccount } = this.vuex_accountInfo
      const showState = (
        auditStatus == 0 &&
        order_status == 10 &&
        xdAccount == loginAccount &&
        paid_type == 1201 &&
        (billDate == this.curDate || billDate == this.setFormatDate(this.curDate))
      )
      return showState
    },
    // 展示门店订单-去支付按钮
    showPayBtn() {
      // paid_type == settleType
      const { auditStatus, order_status, xdAccount, billDate, paid_type } = this.orderInfo
      const { loginAccount } = this.vuex_accountInfo
      const showState = (
        auditStatus == 0 &&
        (order_status == 0 || order_status == 10) &&
        xdAccount == loginAccount &&
        paid_type == 1001 &&
        (billDate == this.curDate || billDate == this.setFormatDate(this.curDate))
      )
      return showState
    },
    // 展示门店订单-提货信息按钮
    showPackupBtn() {
    /* signWay (0, "未签收"),(1, "电子签收"),(2, "纸质签收"),(3, "提货码核销"),(4, "收银台审核触发已签收"),(5, "订单对账"),(6, "超时自动确认收货"),(7, "正票签收触发已签收"),(8, "客户自主确认收货"),(9, "正向销售订单整单逆向触发签收"),(10, "提货码提货销售订单整单换货触发签收");
    * 提货码核销生成提货码，其他不生成*/
      const { commonOrderType, order_status, signWay } = this.orderInfo
      // commonOrderType == orderType
      const showState = (commonOrderType == 19654 || commonOrderType == 19651 || commonOrderType == 19655) && (order_status == 30 || order_status == 35) && signWay == 3
      return showState
    }
  },
  watch: {
    orderInfo(newVal, oldVal) {
      this.newOrderInfo = newVal
      this.againBuyFlag = this.againBuy(newVal)
      this.LogisticsFlag = this.postTmsLogisticsInfo(newVal)
      this.selfFlag = this.self(newVal)
      this.receiveFlag = this.receive(newVal)
      this.goPayFlag = this.goPay(newVal)
      this.deleteShowFlag = this.deleteShow(newVal)
      this.cancelFlag = this.cancelFn(newVal)
      this.cancelTimeFlag = this.cancelTime(newVal)
      this.getTimerOut(newVal)
    }
  },
  mounted() {
    this.againBuyFlag = this.againBuy(this.orderInfo)
    this.LogisticsFlag = this.postTmsLogisticsInfo(this.orderInfo)
    this.selfFlag = this.self(this.orderInfo)
    this.receiveFlag = this.receive(this.orderInfo)
    this.goPayFlag = this.goPay(this.orderInfo)
    this.deleteShowFlag = this.deleteShow(this.orderInfo)
    this.cancelFlag = this.cancelFn(this.orderInfo)
    this.cancelTimeFlag = this.cancelTime(this.orderInfo)
    this.getTimerOut(this.orderInfo)
    // console.log(this.cancelFlag, this.cancelTimeFlag, this.deleteShowFlag, this.goPayFlag, this.receiveFlag, this.selfFlag, this.LogisticsFlag, this.againBuyFlag)
  },
  methods: {
    setFormatDate(time) {
      const orderNextTime = formatDate(new Date(new Date(time).getTime() + (24 * 60 * 60 * 1000)), 'yyyy-mm-dd')
      return orderNextTime
    },
    /*查看提货信息*/
    storeViewPickingInfoFn(orderNo) {
      uni.navigateTo({
        url: '/orders/pickup-Infomation/pickup-Infomation?orderNo=' + orderNo
      });
    },
    /*跳转订单确认页*/
    storeGoPaymentFn(orderNo) {
      uni.navigateTo({
        url: '/payments/payment/payment?orderNo=' + orderNo + '&pageSource=local'
      });
    },
    getTimerOut(e) {
      this.surplusTime = e.limit_time - e.current_time
    },
    onChange(e) {
      this.timeData = e
    },
    cancelTime(obj) {
      const { accountType } = this.vuex_memberInfo
      const { order_status } = obj
      return order_status == 10 && accountType !== '10'
    },
    cancelFn(obj) {
      const { accountType } = this.vuex_memberInfo //  账户类型：10:签约用户/数采；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
      const { cancle_apply_show, paid_button_show, order_status, paid_type } = obj
      var statusList = [9, 10, 20]
      var paidList = [1101, 1102, 1103]
      var accountTypeList = ['10', '39', '40']
      return accountTypeList.includes(accountType) == false && (statusList.includes(order_status) && (cancle_apply_show || (paid_button_show && paidList.includes(paid_type))))
    },
    againBuy(obj) {
      var findSpot = obj.listOrderItems ? obj.listOrderItems.every((item) => !item.buyyer_count.toString().includes('.')) : true // 订单中如果拥有小数点数量的商品。不能购买
      const { accountType } = this.vuex_memberInfo //  账户类型：10:签约用户/数采；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
      const { order_status, final_sent_type, buy_again_button } = obj
      var sentTypeList = [10, 20, 21, 30]
      var accountTypeList = ['10', '39', '40']
      return (accountTypeList.includes(accountType) == false && ((order_status == 60 && sentTypeList.includes(final_sent_type)) || (buy_again_button && findSpot)))
    },
    postTmsLogisticsInfo(obj) {
      const { sent_type, order_status } = obj
      var statusList = [55, 60]
      return (sent_type !== 50 && statusList.includes(order_status))
    },
    self(obj) {
      const {
        sent_type,
        order_status,
        paid_type,
        platform,
        cancle_apply_show,
        authorityList, // 枚举值： 1- 结算 :   2-下单  :3- 审批
        customerSignWay, //customerSignWay  客户签收方式:10-电子签收,20-纸质签收
      } = obj
      var statusList = [40, 45]
      var platformList = [10, 20] //线上订单 40 平台
      // var paid_typeList = [1000, 1001, 1101, 1102, 1103, 1301, 1401]
      // var orderTypeList = [19651, 19654, 19655]
      var sent_typeList = [50, 52]
      /*非账期支付的 以及 账期支付且签收方式为提货码核销的订单展示订单二维码（提货码）
       初始支付方式：1000=>线下订单[在线支付(现款)];1001=>在线支付;1101=>货到付款;1102=>货到付款-现金；1103=>货到付款-pos机；1201=>账期支付;1301=>银行转帐;1401=>电子汇票;*/
      const commonCondition = (paid_type != 1201 || (paid_type == 1201 && customerSignWay == 10)) && sent_typeList.includes(sent_type) && statusList.includes(order_status)
      if (platformList.includes(platform)) { //线上订单判断
        return commonCondition && cancle_apply_show && authorityList.includes(2)
      } else { // 门店
        return commonCondition
      }
    },
    /*确认收货按钮展示规则
    * 1、线上订单(23开头的)逻辑：（当前登录账号与订单的下单账号一致（还是之前的authorityList） || 库管员 ）且 是否自主确认收货（是  1） 且 待收货（60）
    * 2、线下订单(XS开头的)逻辑：（当前登录账号与订单的下单账号一致【这里是变更点(新加的)】（当前登录账号member_id = xdAccountId） || 库管员 ）且 是否自主确认收货（是  1） 且 待收货（60）
    */
    receive(obj) {
      const {
        order_status,
        isConfirmReceipt,
        platform,
        xdAccountId,
        authorityList,
      } = obj
      const { memberId } = this.vuex_accountInfo
      const { accountRole } = this.vuex_memberInfo // account_role '账号角色 [10:管理员,20:采购员,30:库管员,40:需求员,50:部门管理员]
      var platformList = [10, 20] //线上订单 40 平台
      if (platformList.includes(platform)) { //线上订单判断
        return (authorityList.includes(2) || accountRole == 30) && (order_status == 60 && isConfirmReceipt == 1)
      } else { // 门店
        return (memberId == xdAccountId || accountRole == 30) && (order_status == 60 && isConfirmReceipt == 1)
      }
    },
    goPay(obj) {
      const { paid_button_show, order_status } = obj
      return (paid_button_show && order_status == 10)
    },
    deleteShow(obj) {
      const { accountType } = this.vuex_memberInfo //  账户类型：10:签约用户/数采；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
      const { order_status, pageType = '', platform } = obj
      var statusList = [100, 110]
      var accountTypeList = ['10', '39', '40']
      return accountTypeList.includes(accountType) == false && (statusList.includes(order_status) && pageType !== 'detail') && (platform !== 10 && platform !== 20) //门店订单不显示
    },
    async nowPay() {
      const { order_id, paid_amount, limit_time, current_time, paid_type, platform } = this.newOrderInfo
      var surplusTime = limit_time - current_time
      const params = {
        order_id,
        paid_amount,
        surplusTime,
        paid_type,
        code: this.vuex_login_code,
        platform
      }
      var type = paid_type == 1301 ? 'trans' : paid_type == 1001 ? 'pay' : ''
      if (type == 'trans') {
        uni.navigateTo({
          url: `/payments/transfer/index?params=${JSON.stringify(params)}`
        })
      } else {
        uni.navigateTo({
          url: `/payments/cashier/index?params=${JSON.stringify(params)}`
        })
      }
    },
    /*查看提货信息*/
    viewPickingInfoFn(orderNo) {
      uni.navigateTo({
        url: '/orders/pickup-Infomation/pickup-Infomation?orderNo=' + orderNo
      });
    },
    /*跳转订单确认页*/
    goPaymentFn(orderNo) {
      uni.navigateTo({
        url: '/payments/payment/payment?orderNo=' + orderNo + '&pageSource=local'
      });
    },
    deleteOrder() {
      this.confrimFlag = true
    },
    cancel() {
      this.confrimFlag = false
    },
    async confirm() {
      const { order_id } = this.newOrderInfo
      const { loginAccount } = this.vuex_memberInfo
      const params = {
        orderId: order_id,
        loginAccount
      }
      const res = await deleteOrder(params)
      this.confrimFlag = false
      if (res.code == 0) {
        this.$emit('reloadOrder')
        setTimeout(() => { this.$u.toast('删除成功') }, 300)
      } else {
        this.$u.toast(res.message)
      }
    },
    showPop() { // 选择取消订单理由
      const { memberId, loginAccount } = this.vuex_memberInfo
      const {
        order_id,
        order_status,
        // listOrderItems = []
      } = this.newOrderInfo
      var obj = {
        order_id,
        member_id: memberId,
        cancel_order_status: order_status,
        cancel_role: 10,
        cancle_name: loginAccount
        // listOrderRefundItems: listOrderItems.map((item) => ({ refund_count: item.origin_buyer_count, sku_id: item.sku_id, spu_id: item.spu_id }))
      }
      this.$emit('showCancel', obj)
      this.$emit('showPop')
    },
    showCancel() {
      this.$emit('changeShow')
    },
    goDetail(e) { // 查看详情
      uni.navigateTo({
        url: `/orders/moreOrderDetail/index?id=${e.order_id}`
      })
    },
    async confrimRece() { // 确认收货
      const { order_id } = this.newOrderInfo
      const res = await confrimRece({ order_id })
      if (res.errorCode != 0) {
        this.$u.toast(res.msg)
      }
      this.$emit('reloadOrder')
    },
    async addShopCar() { // 再次购买
      const { memberId } = this.vuex_accountInfo
      const { warehouseCode, cityCode } = this.vuex_cityInfo
      var skuIdNumlist = this.newOrderInfo.listOrderItems.map((item) => {
        const { sku_id, sku_code, buyyer_count, inquiry_id } = item
        return { skuId: sku_id, skuCode: sku_code, skuNum: buyyer_count, inquiryId: inquiry_id }
      })
      const params = {
        member_id: memberId,
        cityId: cityCode,
        warehouseId: warehouseCode,
        source: '40', // android=>10;ios=>20;wap=>30;pc=>40
        skuIdNumlist
      }
      const res = await addShopCar(params)
      if (res.code == '0') {
        uni.redirectTo({
          url: '/purchaseOrder/index'
        })
      } else if (res.code == 1) { // 失效商品=此区域无法售卖/已下架/库存不足（实际+虚拟库存）
        this.$u.toast(res.message)
      } else {
        this.$u.toast(res.message)
      }
    },
    goDraw() { // 查看自提信息
      console.log('提货码1111111')
      const { platform } = this.newOrderInfo
      if (platform == 10 || platform == 20) { // 平台
        uni.navigateTo({
          url: '/orders/drawalShop/index?id=' + this.newOrderInfo.order_id + '&paidType=' + this.newOrderInfo.paid_type
        });
      } else {
        uni.navigateTo({
          url: '/orders/pickup-Infomation/pickup-Infomation?orderNo=' + this.newOrderInfo.order_id
        });
      }
    },
    toLogisticsInfoFn() { // 查看物流
      uni.navigateTo({
        url: '/orders/logisticsInfo/index?orderNo=' + this.newOrderInfo.order_id + '&sentType=' + this.newOrderInfo.sent_type
      });
    },
  }
}
</script>

<style scoped lang="scss">
.FooterOrder {
  .time {
    color: #FF5533;
  }
  .footer {
    display: flex;
    justify-content: space-between;
    align-content: center;
    align-items: center;
    .cancel {
      width: 48rpx;
      height: 48rpx;
      position: relative;
      .cancelBtn {
        position: absolute;
        width: 136rpx;
        height: 64rpx;
        border-radius: 8rpx;
        background: #FFFFFF;
        box-shadow: 0 6px 10px 4px rgba(233,233,233,1);
        color: #222222;
        font-size: 24rpx;
        font-weight: 400;
        text-align: center;
        line-height: 64rpx;
        top: -20rpx;
        right: -140rpx;
      }
      image {
        width: 48rpx;
        height: 48rpx;
      }
    }
    .button {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      align-content: center;
      view {
        width: 140rpx;
        height: 48rpx;
        border-radius: 8rpx;
        border: 2rpx solid #DEDEDE;
        margin-right: 20rpx;
        display: flex;
        justify-content: center;
        align-content: center;
        align-items: center;
      }
      view:last-child {
        margin-right: 0rpx;
      }
      .bgbtn {
        background: #FF5533;
        border: 2rpx solid #FF5533 !important;
        color: #FFFFFF;
      }
    }
  }
}
</style>
